#!/bin/bash
PANF=/home/cmbpanfs-01/yanghoch # can be overwritten by bashrc
source ~/.bashrc
source ~/SHELL/isFileEmpty.sh
if [ $# -ne 4 ]; then
	echo "This shell output the html report with 5 link to the following file"
	echo "(1) UCSC genome browser to show the coverage .bed"
	echo "(2) The selecected isoforms"
	echo "(3) The AceView isoforms"
	echo "(4) The selected CDSs"
        echo "(5) The AceView CDSs"
	echo "Those file are expected to be generated in fixed name in the code"
	echo "The input args are:"
	echo "The 1st ptr is gene name"
	echo "The 2nd ptr is chr seq name"
	echo "The 3rd ptr is the range start"
	echo "The 4th ptr is the range end"
	echo "4 ptrs are needed"
	echo "$# is provided" 
	exit 0
fi
# Path for result 
OUT_DIR=$PANF//'UCSC'
OUT_LIST="GeneList.htm"

WIG_PATH=$DATA_DIR/"$2.wig"       # The whole coverage info
WIG_OUT=$TMP_DIR/"$2_$3_$4.wig"   # The extracted coverage info
ACE_PATH=$ACE_DIR/$1.fa           # The whole 


OUT_FILE="$2_$3_$4.bed" 

SELECTED_I="$(basename $1)_I_selected.fa"
SELECTED_CDS="$(basename $1)_CDSs_selected.fa"
# Extract the coverage of the gene region 
~/SHELL/generateCoverageBED.sh $WIG_PATH $3 $4 $OUT_FILE

ACE_DIR=$PANF/AceViewMrna         # The whole AceView isoforms 
ACE_PATH=$ACE_DIR/$2mrna.fa       # The AceView isoforms in a chr
ACEVIEW_I="$1_Ace_I.fa"           # Extracted AceView isoforms output path 
ACEVIEW_CDS="$1_Ace_CDS.fa"       # Extracted AceView isoforms output path 
# Extract the AceView Isoforms
bSingleContig="F"
python ~/SCRIPT/get_seqs_from_fasta.py $ACE_PATH $1 $bSingleContig $ACEVIEW_I
if test -s $ACEVIEW_I; then
	ls $ACEVIEW_I
	echo "Call get_CDSs_from_fasta  $ACEVIEW_I $ACEVIEW_CDS"
	python ~/SCRIPT/get_CDSs_from_fasta.py $ACEVIEW_I $ACEVIEW_CDS
	#\rm $ACEVIEW_I
else
	echo "Couldn't get CDS from AceView sequence" 
	mv $ACEVIEW_I $ACEVIEW_CDS
fi

cp "$ACEVIEW_CDS" "$OUT_DIR"/"$(basename $ACEVIEW_CDS)"
cp "$ACEVIEW_I" "$OUT_DIR"/"$(basename $ACEVIEW_I)"

echo "generate HTML output" 
URL=$(head -n 1 $OUT_FILE)
URL=$(echo $URL | sed 's/^#//g')
SERVER="http://dw408k-2.cmb.usc.edu:8080/ucsc"
echo "<h3><a href=\"$SERVER/$SELECTED_CDS\">$1 CDS</a>" >> "$OUT_DIR"/"$OUT_LIST"
echo "<a href=\"$SERVER/$ACEVIEW_CDS\">AceView CDS </a>" >> "$OUT_DIR"/"$OUT_LIST"
echo "<a href=\"$SERVER/$SELECTED_I\">$1 Isoforms</a>" >> "$OUT_DIR"/"$OUT_LIST"
echo "<a href=\"$SERVER/$ACEVIEW_I\">AceView Isoform</a>" >> "$OUT_DIR"/"$OUT_LIST"
echo "<a href=\"$URL\">$2_$3_$4</a></h3>" >> "$OUT_DIR"/"$OUT_LIST"

mv $OUT_FILE "$OUT_DIR"/"$OUT_FILE"
mv $SELECTED_CDS "$OUT_DIR"/"$SELECTED_CDS"
mv $SELECTED_I "$OUT_DIR"/"$SELECTED_I"

echo "generate BAT file"
BAT_OUT="$OUT_DIR"/"$1.bat"
LOCAL_DIR="C:\\TestGenes"
LOCAL_PATH4CDS=$LOCAL_DIR\\"$SELECTED_CDS"
echo "start $URL" > $BAT_OUT 
echo "perl BlatAndShow.pl human hg18 DNA query,start $LOCAL_PATH4CDS 2>$1.log" >> $BAT_OUT

if [ $TMP_DIR == "./tmp/" ]; then
	echo "Delete tmp dir"
	for file in $(ls ./tmp); do
		\rm ./tmp/$file
	done
	\rmdir "./tmp"
fi
exit
